// Theme switching functionality
function switchTheme(theme) {
    const root = document.documentElement;
    
    // Save user selected theme to localStorage
    localStorage.setItem('theme', theme);
    
    // Apply theme
    if (theme === 'dark') {
        // Apply dark theme
        root.setAttribute('data-theme', 'dark');
    } else if (theme === 'light') {
        // Apply light theme
        root.setAttribute('data-theme', 'light');
    } else {
        // Use default theme (based on system preference or browser default)
        root.removeAttribute('data-theme');
        localStorage.removeItem('theme');
    }
    
    // Update theme selector value
    const themeSelector = document.getElementById('theme-select');
    if (themeSelector) {
        themeSelector.value = theme;
    }
    
    // Reassign random tag colors to adapt to new theme
    assignRandomTagColors();
}

// Assign random color classes to tags
function assignRandomTagColors() {
    // Get all tag elements on the page
    const tags = document.querySelectorAll('.tag');
    
    // First clear all color classes from tags
    tags.forEach(tag => {
        for (let i = 1; i <= 10; i++) {
            tag.classList.remove('tag-color-' + i);
        }
        
        // Generate random number 1-10 to select color class
        const colorClass = 'tag-color-' + Math.floor(Math.random() * 10 + 1);
        tag.classList.add(colorClass);
    });
}

// Restore user selected theme when page loads
document.addEventListener('DOMContentLoaded', function () {
    // Get saved theme from localStorage
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
        switchTheme(savedTheme);
    }
    
    // Ensure theme selector has correct value
    const themeSelector = document.getElementById('theme-select');
    if (themeSelector && savedTheme) {
        themeSelector.value = savedTheme;
    }
    
    // Assign random colors to tags
    assignRandomTagColors();
});